package com.example.back.service.impl;

import java.util.Map;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import com.example.back.jpa.ClientPatientsInfoRepository;
import com.example.back.jpa.CommentRository;
import com.example.back.jpa.DoctorBaseInfoRepository;
import com.example.back.jpa.OrderMainRepository;
import com.example.back.jpa.RxDrugsRepository;
import com.example.back.jpa.RxInfoRepository;
import com.example.back.mapper.InquiryOrderMapper;
import com.example.back.service.InquiryService;
import com.example.common.entity.BaseInfo;
import com.example.common.entity.Comment;
import com.example.common.entity.ClientPatientsInfo;
import com.example.common.entity.ConsultationLog;
import com.example.common.entity.DoctorBaseInfo;
import com.example.common.entity.OrderMain;
import com.example.common.entity.PatientsInfo;
import com.example.common.entity.RxDrugs;
import com.example.common.entity.RxInfo;
import com.example.common.enums.AType;
import com.example.common.enums.ChkStatus;
import com.example.common.enums.DType;
import com.example.common.enums.OCStatus;
import com.example.common.support.ApiException;

import org.javers.spring.annotation.JaversAuditable;
import org.springframework.stereotype.Service;

/**
 * @Author wxy
 * @Date 2021/1/13 14:34
 * @Version 1.0
 */
@Service
public class InquiryServiceImpl implements InquiryService {
    
    @Resource
    private InquiryOrderMapper inquiryOrderMapper;

    @Resource
    private OrderMainRepository orderMainRepository;

    @Resource
    private ClientPatientsInfoRepository clientPatientsInfoRepository;

    @Resource
    private DoctorBaseInfoRepository doctorBaseInfoRepository;

    @Resource
    private RxDrugsRepository rxDrugsRepository;

    @Resource
    private CommentRository commentRository;

    @Resource
    private RxInfoRepository rxInfoRepository;
    /**
     * 服务订单
     */
    @Override
    public Map<String, Object> List(String orderno,int atype,String dname,String cname,int ocstatus,int page,int limit) {
        int skip = (page - 1) * limit;
        if (skip < 0) skip = 0;

        List<Map<String, Object>> query = inquiryOrderMapper.List(orderno, atype, dname, cname, ocstatus, skip, limit);
        int count = inquiryOrderMapper.ListCount(orderno, atype, dname, cname, ocstatus);

        List<Map<String, Object>> list = new ArrayList<>();
        query.forEach(m -> {
            Map<String, Object> o = new HashMap<>();
            o.put("OrderNO", m.get("OrderNO"));
            o.put("AType", AType.valueToDesc(Long.valueOf(m.get("AType").toString()).intValue()));
            o.put("depName", m.get("depName"));
            o.put("dName", m.get("dName"));
            o.put("pName", m.get("Name"));
            o.put("CreateTime", m.get("CreateTime"));
            o.put("AskMoney", m.get("AskMoney"));
            o.put("OCStatus", OCStatus.valueToDesc(Long.valueOf(m.get("OCStatus").toString()).intValue()));
            list.add(o);
        });

        Map<String, Object> res = new HashMap<>();
        res.put("list", list);
        res.put("cnt", count);
        return res;
    }

    /**
     * 对话列表
     */
    @Override
    public Map<String, Object> ImList(String orderno, int page,int limit) {
        int skip = (page - 1) * limit;
        if (skip < 0) skip = 0;

        Map<String, Object> res = new HashMap<>();
        OrderMain order = orderMainRepository.findById(orderno).orElseThrow(()->new ApiException(10000, "订单不存在"));
        
            ClientPatientsInfo p = clientPatientsInfoRepository.findById(order.getPid()).orElseThrow(()->new ApiException(10000, "患者不存在"));
            Map<String, Object> pat = new HashMap<>();
            pat.put("Name", p.getName());
            pat.put("Head", p.getHeader());
            res.put("pat", pat);

            DoctorBaseInfo d = doctorBaseInfoRepository.findById(order.getDcId()).orElseThrow(()->new ApiException(10000, "医生不存在"));
            Map<String, Object> doc = new HashMap<>();
            doc.put("Name", d.getName());
            doc.put("Head", d.getHead());
            res.put("doc", doc);
        

        if(order.getOcId() != null){
        List<Map<String, Object>> imList = inquiryOrderMapper.findByOCID(order.getOcId(), skip, limit);        
        res.put("list", imList);
    }
        return res;
    }

    /**
     * 病历 非本院首诊
     */
    @Override
    public Map<String, Object> DiagnosisOut(String orderno) {
        Map<String, Object> query = inquiryOrderMapper.DiagnosisOut(orderno);
        Map<String, Object> obj = new HashMap<>();
        obj.put("Name", query.get("Name"));
        obj.put("Sex", query.get("Sex"));
        obj.put("Age", query.get("Age"));
        obj.put("FVisitDate", query.get("FVisitDate"));
        obj.put("FHospital", query.get("FHospital"));
        obj.put("FDepartment", query.get("FDepartment"));
        obj.put("FDiagnosis", query.get("FDiagnosis"));
        obj.put("isPregnancy",query.get("isPregnancy") == null ? false : query.get("isPregnancy"));
        obj.put("isLactationPeriod",query.get("isLactationPeriod") == null ? false : query.get("isLactationPeriod"));
        byte ftype = Byte.valueOf(query.get("firstType").toString());
        String firstName = "";
        switch (ftype) {
            case 1:
                firstName = "本院本医生";
                break;
            case 2:
                firstName = "非本院复诊";
                break;
            case 3:
                firstName = "本院其他医生";
                break;        
            default:
                break;
        }
        obj.put("firstName",firstName);
        obj.put("imgs", inquiryOrderMapper.visitImgList((long)query.get("ID")));

        Map<String, Object> detail = new HashMap<>();
        detail.put("detail", obj);
        return detail;
    }

    /**
     * 处方列表
     */
    @Override
    public List<Map<String, Object>> RxOrderList(String orderno) {
        List<Map<String, Object>> rxlist = inquiryOrderMapper.RxOrderList(orderno);
        if(rxlist == null || rxlist.size() == 0)
            return null;

        List<String> RxOrderNOs = rxlist.stream().map(e -> e.get("RxOrderNO").toString()).collect(Collectors.toList());       
        List<RxDrugs> xdList = rxDrugsRepository.findByRxOrderNOs(RxOrderNOs);
        List<RxInfo> zdList = rxInfoRepository.RxInfoList(RxOrderNOs);

        List<Map<String, Object>> list = new ArrayList<>();
        rxlist.forEach(m -> {
            Map<String, Object> o = new HashMap<>();
            int iDType = Long.valueOf(m.get("DType").toString()).intValue();
            if(iDType == 1){
                RxInfo rxinfo = zdList.stream().filter(n -> n.getRxOrderNo().equals(m.get("RxOrderNO"))).findFirst().get();
                Map<String, Object> detail = new HashMap<>();
                detail.put("AVoid", rxinfo.getAvoid());
                detail.put("MedTime", rxinfo.getUseTime());
                detail.put("DrugInfo", rxinfo.getDrugInfo());
                detail.put("TotalDoes", rxinfo.getTotalDoes());
                detail.put("DayCount", rxinfo.getDayCount());
                detail.put("Does", rxinfo.getDoes());
                detail.put("MedWay", rxinfo.getMedWay());
                o.put("detail", detail);
            } else if(iDType == 2){
                List<RxDrugs> detail = xdList.stream().filter(n -> n.getRxOrderNo().equals(m.get("RxOrderNO"))).collect(Collectors.toList()); 
                List<Map<String, Object>> detaill = new ArrayList<>();
                detail.forEach(n -> {
                    Map<String, Object> detailm = new HashMap<>();
                    detailm.put("DrugName", n.getDrugName());
                    detailm.put("Spec", n.getSpec());
                    detailm.put("Num", n.getNum());
                    detailm.put("Suggest", n.getMedWay() + "；每日" + n.getFreq() + "；" + n.getDoes() + n.getDoesUnit() + "/次；" + n.getDay() + "天");
                    detailm.put("Remark", n.getRemark());
                    detaill.add(detailm);
                });
                o.put("detail", detaill);
            }
            o.put("CreateTime", m.get("CreateTime"));
            o.put("RxOrderNO", m.get("RxOrderNO"));
            o.put("DType", m.get("DType"));
            o.put("DTypeName", DType.valueToDesc(iDType));
            o.put("Name", m.get("Name"));
            o.put("Sex", m.get("Sex"));
            o.put("Age", m.get("Age"));
            o.put("depName", m.get("depName"));
            o.put("ChkStatus", ChkStatus.valueToDesc((Long.valueOf(m.get("ChkStatus").toString())).intValue()));
            o.put("OpenDoctor", m.get("OpenDoctor"));
            o.put("ChkDoctor", m.get("ChkDoctor"));
            o.put("FailureReason", m.get("FailureReason"));
            o.put("FailureRemark", m.get("FailureRemark"));
            o.put("Dialectical", m.get("Dialectical"));
            list.add(o);
        }); 

        return list;
    }

    /**
     * 订单评价
     */
    @Override
    public Map<String, Object> Comment(String orderno) {
        Comment c = commentRository.findById(orderno).orElse(new Comment());
        Map<String, Object> Comment = new HashMap<>();
        Comment.put("HScore", c.getHScore());
        Comment.put("HRemark", c.getHRemark());
        Comment.put("DScore", c.getScore());
        Comment.put("DRemark", c.getDRemark());

        Map<String, Object> dinfo = inquiryOrderMapper.docInfo(orderno);

        Map<String, Object> res = new HashMap<>();
        res.put("dinfo", dinfo);
        res.put("Comment", Comment);
        return res;
    }

    /**
     * 删除订单评价
     */
    @Override
    @JaversAuditable
    public String DelComment(String orderno) {
        try {
            commentRository.deleteById(orderno);
            return "";
        } catch (Exception e) {
            //TODO: handle exception
        }
        return "删除失败";
    }
}
